"""
认证管理器 - 统一提供token
"""
import jwt
import time
from typing import Dict, Optional, Any
from config.settings import settings
from common.logger import get_logger

logger = get_logger(__name__)


class AuthManager:
    """认证管理器"""
    
    def __init__(self):
        self.jwt_secret = settings.get("auth.jwt_secret", "default-secret-key")
        self.token_expire_hours = settings.get("auth.token_expire_hours", 24)
        self.algorithm = settings.get("auth.algorithm", "HS256")
    
    def generate_token(self, user_id: str, user_data: Dict[str, Any] = None) -> str:
        """生成JWT token"""
        payload = {
            "user_id": user_id,
            "exp": int(time.time()) + self.token_expire_hours * 3600,
            "iat": int(time.time()),
            "iss": "python-project"
        }
        
        if user_data:
            payload.update(user_data)
        
        token = jwt.encode(payload, self.jwt_secret, algorithm=self.algorithm)
        logger.info(f"为用户 {user_id} 生成token")
        return token
    
    def verify_token(self, token: str) -> Optional[Dict[str, Any]]:
        """验证JWT token"""
        try:
            payload = jwt.decode(token, self.jwt_secret, algorithms=[self.algorithm])
            return payload
        except jwt.ExpiredSignatureError:
            logger.warning("Token已过期")
            return None
        except jwt.InvalidTokenError:
            logger.warning("无效的token")
            return None
    
    def refresh_token(self, token: str) -> Optional[str]:
        """刷新token"""
        payload = self.verify_token(token)
        if payload:
            # 移除过期时间，重新生成
            payload.pop('exp', None)
            payload.pop('iat', None)
            return self.generate_token(payload['user_id'], payload)
        return None
    
    def get_user_id_from_token(self, token: str) -> Optional[str]:
        """从token中获取用户ID"""
        payload = self.verify_token(token)
        return payload.get('user_id') if payload else None
    
    def is_token_expired(self, token: str) -> bool:
        """检查token是否过期"""
        try:
            jwt.decode(token, self.jwt_secret, algorithms=[self.algorithm])
            return False
        except jwt.ExpiredSignatureError:
            return True
        except jwt.InvalidTokenError:
            return True


# 全局认证管理器实例
auth_manager = AuthManager()